package com.wan37.logic.shop.dao.impl;

import com.wan37.logic.shop.dao.CommodityDao;
import com.wan37.logic.shop.domain.entity.CommodityDO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-08-10 20:41
 **/
@Repository
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public class CommodityDaoImpl implements CommodityDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Override
    public boolean add(CommodityDO commodityDO) {
        hibernateTemplate.save(commodityDO);
        return false;
    }

    @Override
    public boolean delete(Integer id) {
        return false;
    }

    @Override
    public boolean update(CommodityDO commodityDO) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("update CommodityDO set number = ? where commodityId = ? and shopId");
        query.setParameter(0, commodityDO.getNumber());
        query.setParameter(1, commodityDO.getCommodityId());
        query.setParameter(2, commodityDO.getShopId());
        query.executeUpdate();
        return false;
    }

    @Override
    public List<CommodityDO> getAll() {
        return (List<CommodityDO>) hibernateTemplate.find("from CommodityDO");
    }

    @Override
    public List<CommodityDO> findCommodityByShopId(String shopId) {
        return (List<CommodityDO>) hibernateTemplate.find("from CommodityDO where shopId = ?", shopId);
    }

    @Override
    public List<CommodityDO> findCommodityByShopIdAndCommodityId(CommodityDO commodityDO) {
        return (List<CommodityDO>) hibernateTemplate.find("from CommodityDO where " +
                "shopId = ? and commodityId = ?", commodityDO.getShopId(), commodityDO.getCommodityId());
    }
}
